<template>
  <div class="contioner">
    <div class="search-form divClass" v-show="headerShow" style="padding-top: 15px">
      <a-form size="small" :model="query" layout="inline">
        <a-form-item label="日期">
          <a-date-picker  popup-container="html" 
            v-model="query.beginDate"
            :style="{ width: '180px' }"
            placeholder="选择日期"
            class="bacClass"
          />至
          <a-date-picker  popup-container="html" 
            v-model="query.enginDate"
            :style="{ width: '180px' }"
            placeholder="选择日期"
            class="bacClass"
          />
        </a-form-item>
        <CorporateSectorCascader
          :configCascader="configCascader"
          @changeCascader="changeCascader"
        />
      </a-form>
      <div class="my-tool-bar" style="margin-bottom: 5px">
        <a-space>
          <el-button v-if="infoType == 1" type="primary" :icon="Search" @click="getList"
            >查询</el-button
          >
          <el-button v-else type="primary" @click="ListFans">返回</el-button>
          <!-- <el-button pain @click="emit('takebiaoji', 0)" plain>返回主页</el-button> -->
        </a-space>
      </div>
    </div>
    <div class="my-divisders">
      <a-divider orientation="center">
        <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
        <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
      </a-divider>
    </div>

    <div style="background-color: #f0f2f5; height: 10px"></div>
    <div :style="{ height: '88%', padding: '10px', overflow: 'aout' }" v-loading="loadings">
      <div style="width: 100%; height: 40%" v-if="infoType == 1">
        <a-tag color="#5e8af5">吨布漏验次数统计表（汇总）</a-tag>
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          @click="agGridClicks"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="tableDataList"
          :columnDefs="tc"
          :localeText="localeText1"
        >
        </AgGridVuesCopys>
      </div>
      <div style="width: 100%; height: 40%" v-if="infoType == 2">
        <a-tag color="#5e8af5">吨布漏验次数统计表（班别）</a-tag>
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          rowSelection="multiple"
          @grid-ready="gridReady2"
          style="height: 100%"
          @click="agGridClicks2"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="tableDataList2"
          :columnDefs="tc2"
          :localeText="localeText1"
        >
        </AgGridVuesCopys>
      </div>
      <div ref="myChart" :style="{ width: '100%', height: '60%' }"></div>
      <div style="width: 100%; height: 100%" v-if="infoType == 3">
        <a-tag color="#5e8af5">吨布漏验次数统计表（验布工个人）</a-tag>
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          rowSelection="multiple"
          @grid-ready="gridReady3"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="tableDataList3"
          :columnDefs="tc3"
          :localeText="localeText1"
        >
        </AgGridVuesCopys>
      </div>
    </div>
  </div>
  <a-modal
    :width="1200"
    v-model:visible="showAddIstours"
    ok-text="关闭"
    :hide-cancel="true"
    @ok="handleOk"
  >
    <template #title> 详情 </template>
    <AgGridVuesCopys :rowHeight="33" :headerHeight="33"
      :suppressCopyRowsToClipboard="true"
      rowSelection="multiple"
      style="height: 300px"
      :defaultColDef="defaultColDef"
      class="ag-theme-alpine"
      :rowData="showAddList"
      :columnDefs="tc4"
      :localeText="localeText1"
    >
    </AgGridVuesCopys>
  </a-modal>
</template>

<script lang="ts" setup>
  import * as echarts from 'echarts'
  
  import { Message } from '@arco-design/web-vue'
  import { ref, reactive, onMounted, watch } from 'vue'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  // 引入element提示
  //引入封装post
  import { post } from '@/api/http'
  import { Search, EditPen } from '@element-plus/icons-vue'
  import dayjs from 'dayjs'
  import { localeText } from '@/api/aggridZw'
  const localeText1: any = ref(localeText)
  const emit = defineEmits(['takebiaoji'])
  const headerShow = ref<boolean>(true)

  const myChart: any = ref()
  const states = () => {
    return echarts.init(myChart.value!)
  }
  const option = ref({
    title: {
      text: '吨布漏验次数走势图',
      /*textVerticalAlign:'center'*/
      top: '5%',
      left: '45%',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['本集团订单准交率', '外加工订单准交率', '厂部订单准交率'],
      top: '5%',
      right: '5%',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %',
      },
    },
    series: [
      {
        name: '',
        type: 'line',
        data: [42, 41, 45, 46, 42, 41, 40, 43, 46, 42, 44, 39],
        label: { formatter: '{c}%' },
        symbolSize: 15,
        lineStyle: {
          width: 8,
        },
      },
      {
        name: '标准值',
        type: 'line',
        data: [40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40],
        label: { formatter: '{c}%', color: 'red' },
        symbolSize: 15,
        lineStyle: {
          color: 'red',
          width: 8,
        },
      },
    ],
  })

  const infoType = ref(1)

  const loadings = ref(false)

  const configCascader = ref<{}>({
    corporateWidth: '200px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '厂区', //公司label
    sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
  })
  const changeCascader = (data: any) => {
    const { corporateId, sectorId, sectorLabel, corporateLabel } = data
    query.planOrderCode = corporateId
  }

  interface Querin {
    beginDate: any
    enginDate: any
    planOrderCode: any
  }
  //getlist初始化接口参数
  let query = reactive<Querin>({
    beginDate: dayjs().format('YYYY-MM-DD'), //当月日期
    enginDate: dayjs().format('YYYY-MM-DD'), //当月日期
    // enginDate: formatDateTime(new Date(Number(new Date().getTime()) + (60 * 1000 * 60 * 24 * 7)), 'yyyy-MM-dd'), //当月日期
    planOrderCode: null,
  })
  function formatDateTime(date: any, format: any) {
    const o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
      'H+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds(), // 毫秒
      a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
      A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return format
  }

  const tableDataList: any = ref([])
  const gridOption = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
  }
  const tableDataList2: any = ref([])
  const gridOption2 = ref()
  const gridReady2 = (params: any) => {
    gridOption2.value = params.api
  }
  const tableDataList3: any = ref([])
  const gridOption3 = ref()
  const gridReady3 = (params: any) => {
    gridOption3.value = params.api
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1,
  }

  const showAddIstours: any = ref(false)
  const showAddList: any = ref([])

  const handleOk = () => {
    showAddIstours.value = false
  }

  const tc = [
    {
      headerName: '织厂单位',
      field: 'firm',
      width: 150,
      cellRenderer: {
        template: `
            <a-space :style="{width:'100%',height:'100%',textAlign:'center'}">
                <a-tag v-if="a" class="tagCss">{{a}}</a-tag>
                <span v-else>汇总</span>
            </a-space>
            `,
        setup(props: any) {
          const a = ref(props.params.data.firm)
          return {
            a,
          }
        },
      },
    },
    {
      headerName: '统计开始时间',
      field: 'queryStart',
      width: 150,
    },
    {
      headerName: '统计结束时间',
      field: 'queryEnd',
      width: 150,
    },
    {
      headerName: '漏验次数',
      field: 'omissionNumber',
      width: 150,
    },
    {
      headerName: '产量',
      field: 'totalYield',
      width: 150,
    },
    {
      headerName: '吨布漏验次数',
      field: 'clothOmissionNumber',
      width: 150,
    },
    {
      headerName: '目标值',
      field: 'omissionTarget',
      width: 150,
    },
    {
      headerName: '详情',
      field: 'doubleYield',
      width: 150,
      cellRenderer: {
        template: `
            <a-space :style="{width:'100%',height:'100%',textAlign:'center'}" @click="a">
                <a-tag class="tagCss">详情</a-tag>
            </a-space>
            `,
        setup(props: any) {
          const a = (e: any) => {
            e = e || window.event
            if (e.stopPropagation) {
              e.stopPropagation()
            } else {
              e.cancelBubble = true
            }
            post({
              url: 'pieceData/Donate/getListByOmissionReport',
              data: props.params.data,
            }).then((res: any) => {
              if (res.code == 200) {
                showAddList.value = res.data
                showAddIstours.value = true
              } else {
                Message.error(res.message)
              }
            })
          }
          return {
            a,
          }
        },
      },
    },
  ]
  const tc2 = [
    {
      headerName: '部门',
      field: 'department',
      width: 150,
      cellRenderer: {
        template: `
            <a-space :style="{width:'100%',height:'100%',textAlign:'center'}">
                <a-tag v-if="a" class="tagCss">{{a}}</a-tag>
                <span v-else>汇总</span>
            </a-space>
            `,
        setup(props: any) {
          const a = ref(props.params.data.department)
          return {
            a,
          }
        },
      },
    },
    {
      headerName: '统计开始时间',
      field: 'queryStart',
      width: 150,
    },
    {
      headerName: '统计结束时间',
      field: 'queryEnd',
      width: 150,
    },
    {
      headerName: '漏验次数',
      field: 'omissionNumber',
      width: 150,
    },
    {
      headerName: '产量',
      field: 'totalYield',
      width: 150,
    },
    {
      headerName: '吨布漏验次数',
      field: 'clothOmissionNumber',
      width: 150,
    },
    {
      headerName: '目标值',
      field: 'omissionTarget',
      width: 150,
    },
    {
      headerName: '详情',
      field: 'doubleYield',
      width: 150,
      cellRenderer: {
        template: `
            <a-space :style="{width:'100%',height:'100%',textAlign:'center'}" @click="a">
                <a-tag class="tagCss">详情</a-tag>
            </a-space>
            `,
        setup(props: any) {
          const a = (e: any) => {
            e = e || window.event
            if (e.stopPropagation) {
              e.stopPropagation()
            } else {
              e.cancelBubble = true
            }
            post({
              url: 'pieceData/Donate/getListByOmissionReport',
              data: props.params.data,
            }).then((res: any) => {
              if (res.code == 200) {
                showAddList.value = res.data
                showAddIstours.value = true
              } else {
                Message.info(res.message)
              }
            })
          }
          return {
            a,
          }
        },
      },
    },
  ]

  const tc3 = [
    {
      headerName: '员工',
      field: 'empName',
      width: 150,
      cellRenderer: {
        template: `
                <span v-if="a">{{a}}</span>
                <span v-else>汇总</span>
            `,
        setup(props: any) {
          const a = ref(props.params.data.empName)
          return {
            a,
          }
        },
      },
    },
    {
      headerName: '统计开始时间',
      field: 'queryStart',
      width: 150,
    },
    {
      headerName: '统计结束时间',
      field: 'queryEnd',
      width: 150,
    },
    {
      headerName: '漏验次数',
      field: 'omissionNumber',
      width: 150,
    },
    {
      headerName: '产量',
      field: 'totalYield',
      width: 150,
    },
    {
      headerName: '吨布漏验次数',
      field: 'clothOmissionNumber',
      width: 150,
    },
    {
      headerName: '目标值',
      field: 'omissionTarget',
      width: 150,
    },
    {
      headerName: '详情',
      field: 'doubleYield',
      width: 150,
      cellRenderer: {
        template: `
            <a-space :style="{width:'100%',height:'100%',textAlign:'center'}" @click="a">
                <a-tag class="tagCss">详情</a-tag>
            </a-space>
            `,
        setup(props: any) {
          const a = (e: any) => {
            e = e || window.event
            if (e.stopPropagation) {
              e.stopPropagation()
            } else {
              e.cancelBubble = true
            }
            post({
              url: 'pieceData/Donate/getListByOmissionReport',
              data: props.params.data,
            }).then((res: any) => {
              if (res.code == 200) {
                showAddList.value = res.data
                showAddIstours.value = true
              } else {
                Message.info(res.message)
              }
            })
          }
          return {
            a,
          }
        },
      },
    },
  ]

  const tc4 = [
    {
      headerName: '制单时间',
      field: 'registerTime',
      width: 150,
    },
    {
      headerName: '公司',
      field: 'firmName',
      width: 150,
    },
    {
      headerName: '组别',
      field: 'zuName',
      width: 150,
    },
    {
      headerName: '员工姓名',
      field: 'empName',
      width: 150,
    },
    {
      headerName: '员工工号',
      field: 'empNo',
      width: 150,
    },
    {
      headerName: '原因',
      field: 'reason',
      width: 150,
    },
  ]

  const agGridClicks = () => {
    try {
      if (gridOption.value.getSelectedRows()[0].firmId == null) {
        // Message.error('汇总数据!')
        return
      }
      selectJt2()
      selectJt2s()
    } catch (error) {
      return
    }
  }

  const agGridClicks2 = () => {
    try {
      if (gridOption2.value.getSelectedRows()[0].department == null) {
        // Message.error('汇总数据!')
        return
      }
      selectJt3()
    } catch (error) {
      return
    }
  }

  //初始化
  onMounted(async () => {
    selectJt()
  })

  function selectJt() {
    loadings.value = true
    post({
      url: 'qms/report/omissionReportByFirm',
      data: {
        // "firmId": query.planOrderCode, //公司ID
        firmId: query.planOrderCode == '' ? null : query.planOrderCode, //公司ID
        dateStart: query.beginDate,
        dateEnd: query.enginDate,
      },
    })
      .then((res: any) => {
        if (res.code == 200) {
          // a.concat(b)
          tableDataList.value = res.data.list.concat(res.data.totalMap)
          loadings.value = false
        } else {
          loadings.value = false
          Message.error(res.message)
        }
      })
      .finally(() => {
        loadings.value = false
      })
  }
  function selectJt2() {
    loadings.value = true
    post({
      url: 'qms/report/omissionReportByDepartment',
      data: {
        // "firmId": query.planOrderCode, //公司ID
        firmId: gridOption.value.getSelectedRows()[0].firmId, //公司ID
        dateStart: query.beginDate,
        dateEnd: query.enginDate,
      },
    })
      .then((res: any) => {
        if (res.code == 200) {
          tableDataList2.value = res.data.list.concat(res.data.totalMap)
          infoType.value = 2
          loadings.value = false
        } else {
          Message.error(res.message)
        }
      })
      .finally(() => {
        loadings.value = false
      })
  }

  function selectJt2s() {
    post({
      url: 'qms/report/omissionReportByDepartmentByChart',
      data: {
        firmId: gridOption.value.getSelectedRows()[0].firmId, //公司ID
        dateStart: query.beginDate,
        dateEnd: query.enginDate,
      },
    }).then((res: any) => {
      const state = states()
      option.value.legend.data = res.data.map((p: any) => p.department)
      option.value.xAxis.data = res.data[0].data.map((p: any) => p.dateDay)
      res.data.forEach((opo: any, index: any) => {
        option.value.series[index] = {
          name: opo.department,
          type: 'line',
          label: { formatter: '{c}', show: true, position: 'top', distance: 10 },
          symbolSize: 15,
          lineStyle: {
            width: 8,
          },
          data: opo.data.map((io: any) => {
            return io.clothOmissionNumber
          }),
        }
      })
      state.setOption(option.value)
    })
  }

  function selectJt3() {
    loadings.value = true
    post({
      url: 'qms/report/omissionReportByEmp',
      data: {
        // "firmId": query.planOrderCode, //公司ID
        firmId: gridOption2.value.getSelectedRows()[0].firmId, //公司ID
        departmentId: gridOption2.value.getSelectedRows()[0].departmentId, //公司ID
        dateStart: query.beginDate,
        dateEnd: query.enginDate,
      },
    })
      .then((res: any) => {
        if (res.code == 200) {
          tableDataList3.value = res.data.list.concat(res.data.totalMap)
          infoType.value = 3
          loadings.value = false
        } else {
          Message.error(res.message)
        }
      })
      .finally(() => {
        loadings.value = false
      })
  }

  const getList = () => {
    selectJt()
  }
  const ListFans = () => {
    if (infoType.value != 1) {
      infoType.value = infoType.value - 1
    }
  }
</script>
<style scoped>
  .contioner {
    height: 100%;
    background: #fff;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
